package hxy.dragon.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class RpcClient {
    public static void main(String[] args) {
        try {
            // 创建动态代理对象
            HelloService service = (HelloService) Proxy.newProxyInstance(
                    HelloService.class.getClassLoader(),
                    new Class<?>[] { HelloService.class },
                    new RpcInvocationHandler("localhost", 8888)
            );

            // 调用远程方法
            String result = service.hello("Alice");
            System.out.println("Result from server: " + result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 定义动态代理的 InvocationHandler
    static class RpcInvocationHandler implements InvocationHandler {
        private final String host;
        private final int port;

        public RpcInvocationHandler(String host, int port) {
            this.host = host;
            this.port = port;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Socket socket = new Socket(host, port);

            // 向服务端发送请求
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(method.getName()); // 方法名
            oos.writeObject(args); // 参数列表

            // 接收服务端返回的结果
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Object result = ois.readObject();

            oos.close();
            ois.close();
            socket.close();

            return result;
        }
    }
}
